package cn.bjxy.shishaolong.system.service;

import cn.bjxy.shishaolong.system.entity.Resources;
import cn.bjxy.shishaolong.system.mapper.ResourcesMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 时少龙
 * @since 2019-03-31
 */
@Service
public class ResourcesServiceImpl extends ServiceImpl<ResourcesMapper, Resources> implements IResourcesService {

    @Autowired
    private ResourcesMapper resourcesMapper;


    /**
     * 获取展开所有已选的资源树
     *
     * @param roleId
     * @return
     * @throws Exception
     */
    @Override
    public List<Resources> queryAllAndChecked(Integer roleId) throws Exception {
        List<Resources> resourcesList = resourcesMapper.queryAllAndChecked(roleId);
        return getResourceTree(resourcesList);
    }

    @Override
    public List<Resources> queryResourcesByUserId(Integer userId) {
        return resourcesMapper.queryResourcesByUserId(userId);
    }

    @Override
    public List<String> queryResourcesKeysByUserId(Integer userId) {
        List<Resources> resourcesList = this.queryResourcesByUserId(userId);
        ArrayList<String> keyList = null;
        if (resourcesList != null && resourcesList.size() > 0) {
            keyList = new ArrayList<>();
            for (Resources res : resourcesList) {
                keyList.add(res.getKey());
            }
        }
        return keyList;
    }

    private List<Resources> getResourceTree(List<Resources> resourcesList) throws Exception {
        List<Resources> list = new ArrayList();
        Map<Integer, Resources> map = new HashMap<>();

        //处理
        for (Resources sysResources : resourcesList) {
//			sysResources.setExpand(true);
            if (sysResources.getPid() == -1) {
                list.add(sysResources);
                map.put(sysResources.getTid(), sysResources);
            } else {
                Resources parent = map.get(sysResources.getPid());
                if (parent == null) {
                    continue;
                }
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList());
                }
                parent.getChildren().add(sysResources);
                map.put(sysResources.getTid(), sysResources);
            }
        }
        for (Resources resource : list) {
//			if(resource.getChildren()!=null){
//				resource.setChecked(false);
//			}
            resourceChild(resource);
        }
        return list;
    }

    void resourceChild(Resources resource) {
        if (resource.getChildren() != null) {
            resource.setChecked(false);
            for (Resources temp : resource.getChildren()) {
                resourceChild(temp);
            }
        }
    }
}
